package de.melistik.smugmugsync.connect;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.kallasoft.smugmug.api.json.v1_2_1.APIVersionConstants;

public class SmugMugUpload {

	Logger LOGGER = Logger.getLogger(SmugMugUpload.class.getName());
	private SmugMugConnection connection;

	public SmugMugUpload(SmugMugConnection connection) {
		this.connection = connection;
	}

	public int uploadFiles(List<File> fileList, int albumId) {
		int uploaded = 0;
		for (File pic : fileList) {
			try {
				long fileSize = pic.length();
				Date start = new Date();
				LOGGER.log(Level.INFO, "start upload " + pic.getName());
				com.kallasoft.smugmug.api.json.v1_2_1.images.UploadHTTPPut upload = new com.kallasoft.smugmug.api.json.v1_2_1.images.UploadHTTPPut();
				upload.execute(APIVersionConstants.BINARY_UPLOAD_SERVER_URL,
						connection.getResponse().getSessionID(), albumId, null,
						pic.getName(), new FileInputStream(pic));
				Date stop = new Date();
				long time = stop.getTime() - start.getTime();
				int seconds = (int) (time / 1000);
				int bytesPerSec = (int) (fileSize / seconds);
				int kiloBytesPerSecond = bytesPerSec / 1024;
				LOGGER.log(Level.INFO, "...finished in " + seconds
						+ " seconds @ " + kiloBytesPerSecond
						+ " kilobytes/sec\n");
				uploaded++;
			} catch (FileNotFoundException ex) {
				LOGGER.log(Level.SEVERE, null, ex);
			}
		}
		return uploaded;
	}

	public String uploadFile(File pic, int albumId) {
		String result = null;
		try {
			long fileSize = pic.length();
			Date start = new Date();
			LOGGER.log(Level.INFO, "start upload " + pic.getName());
			com.kallasoft.smugmug.api.json.v1_2_1.images.UploadHTTPPut upload = new com.kallasoft.smugmug.api.json.v1_2_1.images.UploadHTTPPut();
			upload.execute(APIVersionConstants.BINARY_UPLOAD_SERVER_URL,
					connection.getResponse().getSessionID(), albumId, null,
					pic.getName(), new FileInputStream(pic));
			Date stop = new Date();
			long time = stop.getTime() - start.getTime();
			int seconds = (int) (time / 1000);
			int bytesPerSec = (int) (fileSize / (seconds <= 0 ? 1 : seconds));
			int kiloBytesPerSecond = bytesPerSec / 1024;
			result = +seconds + " seconds @ " + kiloBytesPerSecond + " kb/sec";
			LOGGER.log(Level.INFO, result);
		} catch (FileNotFoundException ex) {
			LOGGER.log(Level.SEVERE, null, ex);
		}
		return result;
	}
}
